package com.rui.study.algorithm.L_深入理解JVM_JDK动态代理Proxy与cglib;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class TestDynamicProxy implements InvocationHandler {

    private Object target;

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("开始");
        return method.invoke(target, args);
    }

    public Object getProxy(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    interface Foo {
        void sing();
        void dance();
    }

    static class FooImpl implements Foo {
        @Override
        public void sing() {
            System.out.println("FooImpl.sing()..");
        }

        @Override
        public void dance() {
            System.out.println("FooImpl.dance()..");
        }
    }

    public static void main(String[] args) {
        // 保存生成的代理类到磁盘
        System.getProperties().put("sun.misc.ProxyGenerator.saveGeneratedFiles", "true");

        TestDynamicProxy testDynamicProxy = new TestDynamicProxy();
        Foo proxy1 = (Foo) testDynamicProxy.getProxy(new FooImpl());
        proxy1.sing();
        proxy1.dance();
        proxy1.hashCode();
        proxy1.toString();

    }


}
